import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
import { CreateBlogTagDto } from './dto/create-blog_tag.dto';
import { UpdateBlogTagDto } from './dto/update-blog_tag.dto';
import { BlogTag } from './entities/blog_tag.entity';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';

@Injectable()
export class BlogTagService {
  @InjectRepository(BlogTag)
  private blogTagRepository: Repository<BlogTag>

  async createCategory(createBlogTagDto: CreateBlogTagDto) {
    const category = new BlogTag()
    category.value = createBlogTagDto.value
    return await this.blogTagRepository.save(category)
  }

  async findAll() {
    return await this.blogTagRepository.find()
  }

  async findOneById(id: number) {
    const category =  await this.blogTagRepository.findOneBy({
      id: id
    })
    if(!category) {
      throw new HttpException('没有找到此分类', HttpStatus.BAD_REQUEST)
    }
    return category
  }

  async update(updateBlogTagDto: UpdateBlogTagDto) {
    const category = await this.findOneById(updateBlogTagDto.id)
    category.value = updateBlogTagDto.value
    try {
      const updateCategory = await this.blogTagRepository.save(category);
      return updateCategory
    } catch (error) {
      throw new HttpException('更新失败', HttpStatus.BAD_REQUEST)
    } 
  }

  removeById(id: number) {
    return this.blogTagRepository.delete(id);
  }
}
